import { Injectable, Inject } from '@nestjs/common';
import { Repository } from 'typeorm';
import { Photo } from './entities/photo.entity';
import { CreatePhotoDto } from './dto/create-photo.dto';
import CustomException from '../common/exception';
import { UpdatePhotoDto } from './dto/update-photo.dto';

@Injectable()
export class PhotoService {
  constructor(
    @Inject('PHOTO_REPOSITORY')
    private readonly photoRepository: Repository<Photo>,
  ) {}

  async findAll(): Promise<Photo[]> {
    const res = await this.photoRepository.find();
    if (res.length) {
      return res;
    } else {
      throw new CustomException.NotFoundException();
    }
  }

  async findOne(id: string): Promise<Photo> {
    // throw new CustomException.NotFoundException();
    return await this.photoRepository.findOne(id);
  }

  async create(createPhotoDto: CreatePhotoDto) {
    const result = await this.photoRepository.save(createPhotoDto);
    return {
      statusCode: 200,
      message: '照片添加成功',
      data: result,
    };
  }

  async update(updatePhotoDto: UpdatePhotoDto) {
    return await this.photoRepository.update(updatePhotoDto.id, updatePhotoDto);
  }

  async delete(photoId: number) {
    const result = await this.photoRepository.delete({ id: photoId });
    return { statusCode: 200, message: '删除成功', data: result };
  }
}
